package org.example.day05;

/**
 * 第二章节2.2.11: 同步synchronized方法无线等待与解决
 */
//死循环
public class MyThread9 {
    //case1: ★★★ 死循环
//    synchronized public void methodA(){
//        System.out.println("methodA begin");
//        boolean isContinueRun = true;
//        while(isContinueRun){
//
//        }
//        System.out.println("methodA end");
//    }
//    synchronized public void methodB(){
//        System.out.println("methodB begin");
//        System.out.println("methodB end");
//    }

    //case2: ☆☆☆ 解决  (使用同步代码块,自定义锁对象,不使用synchronized修饰方法。)
    Object object1 = new Object();
    public void methodA() {
        synchronized (object1) {
            System.out.println("methodA begin");
            boolean isContinueRun = true;
            while (isContinueRun) {

            }
            System.out.println("methodA end");
        }
    }

    Object object2 = new Object();
    public void methodB() {
        synchronized (object2) {
            System.out.println("methodB begin");
            System.out.println("methodB end");
        }
    }

    public static void main(String[] args) {
        MyThread9 m9 = new MyThread9();
        Thread9A ta = new Thread9A(m9);
        ta.start();
        Thread9B tb = new Thread9B(m9);
        tb.start();
    }
}

class Thread9A extends Thread {
    private MyThread9 m9;

    public Thread9A(MyThread9 m9) {
        this.m9 = m9;
    }

    @Override
    public void run() {
        m9.methodA();
    }
}

class Thread9B extends Thread {
    private MyThread9 m9;

    public Thread9B(MyThread9 m9) {
        this.m9 = m9;
    }

    @Override
    public void run() {
        m9.methodB();
    }
}